﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using JonSkeet.Ebcdic;

namespace Qcenter
{
    public partial class QmessageForm : Form
    {
        public QmessageForm()
        {
            InitializeComponent();
        }


        #region 公用參數

        string[] myArgs;
        string strLocalIP;
        int intLoaclPort;
        string CenterIP;
        int CenterPort;
        Socket Server;
        #endregion


        public void sendTita(string titaString)
        {
            textBoxUpdateSN.Text = DateTime.Now.ToString("mmssffff");//用時間當序號
            textBoxUpd1.Text = "50501670" + textBoxUpdateSN.Text;
            // textBoxHeadSn.Text = string.Format("{0:000}", (Convert.ToInt32(textBoxHeadSn.Text) + 1));
            textBoxHeadSn.Text = DateTime.Now.ToString("ssf");
            //檔頭序號，重覆機率高?


            byte[] byteAPText, debugbyteAPText2;

            string TitaString = titaString;// textBoxUpd1.Text + textBoxUpdateSN.Text + TitaMsg.Text;
            writeLog(TitaString, "Tita");

            byteAPText = EbcdicEncoding.GetEncoding("EBCDIC-US").GetBytes(TitaString);

            string TitaLenth = string.Format("{0:0000}", (Encoding.GetEncoding("big5").GetByteCount(TitaString) + 12));

            byte length1 = byte.Parse(TitaLenth.Substring(0, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            byte length2 = byte.Parse(TitaLenth.Substring(2, 2), System.Globalization.NumberStyles.AllowHexSpecifier);

            byte sn1 = byte.Parse(textBoxHeadSn.Text.Substring(0, 1));
            byte sn2 = byte.Parse(textBoxHeadSn.Text.Substring(1, 1));
            byte sn3 = byte.Parse(textBoxHeadSn.Text.Substring(2, 1));

            byte[] s1 = EbcdicEncoding.GetEncoding("EBCDIC-US").GetBytes(textBoxHeadSn.Text.Substring(0, 1));
            byte[] s2 = EbcdicEncoding.GetEncoding("EBCDIC-US").GetBytes(textBoxHeadSn.Text.Substring(1, 1));
            byte[] s3 = EbcdicEncoding.GetEncoding("EBCDIC-US").GetBytes(textBoxHeadSn.Text.Substring(2, 1));
            sn1 = s1[0];
            sn2 = s2[0];
            sn3 = s3[0];

            byte[] HeaderStr = { 0x0f, 0x0f, 0x0f, 0x00, length1, length2, 0x01, sn1, sn2, sn3, 0x0f, 0x0f };//ok


            //完整電文 =  Header(12 Bytes) + AP Text (466 Bytes)
            byte[] byteMsg = new byte[byteAPText.Length + 12];
            // byte[] byteMsg = new byte[Encoding.GetEncoding("big5").GetByteCount(TitaString) + 12];

            //串上檔頭Header
            for (int i = 0; i < HeaderStr.Length; i++)
            {
                byteMsg[i] = HeaderStr[i];
            }

            //第12Byte以後串上AP Text
            for (int i = 0; i < byteAPText.Length; i++)
            {
                byteMsg[i + 12] = byteAPText[i];
            }

            labelTitaSend.Text = "送出電文中...";

            txtDnMsg.Text = "";
            int iSendCount = 0;
            Server.SendTimeout = 10000;
            Server.ReceiveTimeout = 15000;
            iSendCount = Server.Send(byteMsg);

            labelTitaSend.Text = "送出電文完成, (" + iSendCount.ToString() + " )bytes";

            //-------------------------------------------------------------------------
            byte[] buffer = new byte[2000];
            String data = null;
            int recv = 0;

            toolStripStatusLabelTota.Text = "等待主機回應中...";

            Application.DoEvents();
            recv = Server.Receive(buffer);

            debugbyteAPText2 = new byte[buffer.Length - 12];

            for (int i = 12; i < buffer.Length; i++)
            {
                debugbyteAPText2[i - 12] = buffer[i];
            }

            if (recv > 0)
            {
                toolStripStatusLabelTota.Text = "主機已回應->(" + recv.ToString() + ")bytes";

                Application.DoEvents();
                txtDnMsg.Text = EbcdicEncoding.GetEncoding(950).GetString(buffer);
                publicByte = debugbyteAPText2;
                textBoxTota.Text = EbcdicEncoding.GetEncoding(950).GetString(debugbyteAPText2);
                writeLog(textBoxTota.Text, "Tota");

            }

            writeLog(textBoxTota.Text, "Tota");
            toolStripTextBoxType.Clear();


            toolStripTextBoxType.Focus();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            myArgs = Environment.GetCommandLineArgs();//參數
            textBoxUpdateSN.Text = DateTime.Now.ToString("mmssffff");//用時間當序號
            textBoxUpd1.Text = "50501670" + textBoxUpdateSN.Text;

            strLocalIP = "10.100.15.185";
            intLoaclPort = 3102;
            CenterIP = "10.128.3.33";
            CenterPort = 2910;

            Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); //建立客户端套接字
            IPAddress localIp = IPAddress.Parse(strLocalIP);

            IPEndPoint lep = new IPEndPoint(localIp, intLoaclPort);
            Server.Bind(lep);

            IPAddress adr = IPAddress.Parse(CenterIP);
            IPEndPoint ep = new IPEndPoint(adr, CenterPort);
            Server.Connect(ep); //完成绑定
        }


        private void writeLog(string sendstr, string sendType)
        {
            string logName = "d:\\" + toolStripTextBoxType.Text + "_" + sendType + DateTime.Now.ToString(" yMMdd-hhmmss") + ".log";
            using (StreamWriter sw = new StreamWriter(logName, true))
            {
                sw.WriteLine(String.Format("{0:yy-MM-dd HHmmsss} : ", DateTime.Now));
                sw.WriteLine(sendstr);
            }
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            if (myArgs.Length > 1)
            {
                this.WindowState = FormWindowState.Minimized;

                this.Close();
            }
            toolStripTextBoxType.Focus();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            sendTita(TitaMsg.Text);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Server.Shutdown(SocketShutdown.Both);
            //Server.Close();

        }

        private void toolStripTextBoxType_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TitaMsg.Clear();
                TitaMsg.Focus();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] byteAPText, debugbyteAPText2;
            byteAPText = EbcdicEncoding.GetEncoding("EBCDIC-US").GetBytes("中文abc");
            debugbyteAPText2 = EbcdicEncoding.GetEncoding(int.Parse(toolStripTextBoxCodePage.Text)).GetBytes("中文abc");
            textBox2.Text = EbcdicEncoding.GetEncoding(int.Parse(toolStripTextBoxCodePage.Text)).GetString(debugbyteAPText2);
            publicByte = debugbyteAPText2;
        }
        byte[] publicByte;
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //textBoxTota.Text = EbcdicEncoding.GetEncoding(int.Parse(toolStripTextBoxCodePage.Text)).GetString(publicByte);


        }

        private void toolStripTextBoxCodePage_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                textBoxTota.Text = EbcdicEncoding.GetEncoding(int.Parse(toolStripTextBoxCodePage.Text)).GetString(publicByte);
            }
            catch (Exception)
            {

                MessageBox.Show("error");
            }

        }


    }
}
